/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: AuthenticateSubmitActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.webank.facelight.contants.WbCloudFaceContant;
import com.webank.facelight.contants.WbFaceError;
import com.webank.facelight.contants.WbFaceVerifyResult;
import com.webank.facelight.listerners.WbCloudFaceVeirfyLoginListner;
import com.webank.facelight.listerners.WbCloudFaceVeirfyResultListener;
import com.webank.facelight.tools.WbCloudFaceVerifySdk;
import com.webank.facelight.ui.FaceVerifyStatus;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.account.presenter.AuthenticateSubmitPresenter;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.utils.FileTools;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.utils.VerifyUtil;
import io.bhex.baselib.images.CImageLoader;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.utils.crop.ImgPickHandler;
import io.bhex.baselib.utils.crop.ImgPickHelper;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnDismissListener;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.account.KycApi;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.account.bean.kyc.KycLevelBean;
import io.bhex.sdk.account.bean.kyc.LvTwoSubmitResponse;
import io.bhex.sdk.account.bean.kyc.SdkPrepareInfoBean;
import io.bhex.sdk.config.bean.KycInfoConfigResponse;
import io.bhex.sdk.trade.bean.TwoVerifyBean;
import io.bhex.sdk.utils.UtilsApi;
import io.bhex.sdk.utils.bean.UploadImgResponse;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * ================================================
 * 描   述：KYC上传提交照片
 *
 * KYC 二级验证
 * ================================================
 */

public class AuthenticateSubmitActivity extends BaseActivity<AuthenticateSubmitPresenter,AuthenticateSubmitPresenter.AuthenticateSubmitUI> implements AuthenticateSubmitPresenter.AuthenticateSubmitUI, View.OnClickListener , EasyPermissions.PermissionCallbacks{
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 0x0;
    private static final int FILECHOOSER_RESULTCODE = 0x1;
    private static final int WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 0x2;
    private static final int REQUEST_CODE_TWO_VERIFY = 0x09;
    private static final String TAG = "KYC-Lv2";
    private AlertView selectPhotoAlert;
    private String[] selectPhotoWayArray;
    private String photoUrl="";
    private String photoUrl2="";
    private boolean bindGA;
    private String mobile;
    private String email;
    private boolean isVerifyEmail;
    private ImageView photoImg1;
    private ImageView photoImg2;
    private KycLevelBean kycLevelBean;
    private boolean faceCompare;
    private TextView authImg2Title;
    private ImageView authImg2Example;
    private TextView authImg2Tips;
    private ImageView authImg1Example;
    private TextView authImg1Title;
    private TextView authImg1Tips;
    private TextView totalTips;

    @Override
    protected int getContentView() {
        return R.layout.activity_authenticate_submit_layout;
    }

    @Override
    protected AuthenticateSubmitPresenter createPresenter() {
        return new AuthenticateSubmitPresenter();
    }

    @Override
    protected AuthenticateSubmitPresenter.AuthenticateSubmitUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();
        Toolbar toolbar= findViewById(R.id.toolbar);
        CollapsingToolbarLayout collapsingToolbarLayout= findViewById(R.id.collapsing_toolbar);
        // 硬编码黑白版Toolbar标题栏title字色
        collapsingToolbarLayout.setCollapsedTitleTextColor(SkinColorUtil.getDark(this));
        collapsingToolbarLayout.setExpandedTitleColor(SkinColorUtil.getDark(this));

        //显示返回按钮
        setSupportActionBar(toolbar);
        ActionBar actionBar=getSupportActionBar();
        if (actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        Intent intent = getIntent();
        if (intent != null) {
            kycLevelBean = (KycLevelBean) intent.getSerializableExtra("kycLevelBean");
            if (kycLevelBean.getCountryCode().equalsIgnoreCase("CN")) {
                viewFinder.textView(R.id.btn_submit).setText(getString(R.string.string_submit));
            }
        }

        photoImg1 = viewFinder.imageView(R.id.auth_img1);
        authImg1Example = viewFinder.imageView(R.id.auth_img1_example_img);
        authImg1Title = viewFinder.textView(R.id.title1);
        authImg2Title = viewFinder.textView(R.id.title2);
        authImg2Example = viewFinder.imageView(R.id.auth_img2_example_img);
        authImg1Tips = viewFinder.textView(R.id.descripe1);
        authImg2Tips = viewFinder.textView(R.id.descripe2);
        totalTips = viewFinder.textView(R.id.auth_img_require_tips);
        photoImg2 = viewFinder.imageView(R.id.auth_img2);
        setImgSize(photoImg1);
        setImgSize(authImg1Example);
        setImgSize(photoImg2);
        setImgSize(authImg2Example);

//        if (CommonUtil.isBhex(this)) {
//            viewFinder.imageView(R.id.auth_img2_example_img).setImageResource(R.mipmap.icon_kyc_positive_signature);
//        }else{
//            viewFinder.imageView(R.id.auth_img2_example_img).setImageResource(R.mipmap.icon_kyc_positive_signature);
//        }

        if (kycLevelBean != null) {
            faceCompare = kycLevelBean.isFaceCompare();
            switchViewKYCStatus(faceCompare);
        }

        selectPhotoWayArray = new String[]{getString(R.string.string_take_photo),getString(R.string.string_gallery)};

    }

    private void switchViewKYCStatus(boolean faceCompare) {
        if (faceCompare) {
            //需要人脸比对：身份证正反面照片上传
            authImg1Example.setImageResource(R.mipmap.icon_kyc_position_new);
            authImg2Example.setImageResource(R.mipmap.icon_kyc_negative);
            authImg2Title.setText(getString(R.string.string_negative_photo_tips));
            authImg2Tips.setText(getString(R.string.string_negative_photo_tips2));


        }else{
            //不需要人脸比对： 身份证正面照+手持正面照
            authImg1Example.setImageResource(R.mipmap.icon_kyc_positive);
            authImg2Example.setImageResource(R.mipmap.icon_kyc_positive_signature);
            authImg2Title.setText(getString(R.string.string_positive_signature_photo_tips2));
            authImg2Tips.setText(getString(R.string.string_positive_signature_photo_tips3));
        }
    }

    /**
     * 设置图片尺寸
     * @param imageView
     */
    private synchronized void setImgSize(ImageView imageView) {
        int screenWidth = PixelUtils.getScreenWidth();
        int imgWidth = (screenWidth - PixelUtils.dp2px(30)*2)/2;
        ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) imageView.getLayoutParams();
        layoutParams.width = imgWidth;
        layoutParams.height = imgWidth;
        imageView.setLayoutParams(layoutParams);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.auth_img1).setOnClickListener(this);
        viewFinder.find(R.id.auth_img2).setOnClickListener(this);
        viewFinder.find(R.id.btn_submit).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.auth_img1:
                showSelectPhoto(true);
                break;
            case R.id.auth_img2:
                showSelectPhoto(false);
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(photoUrl)){
                    ToastUtils.showLong(this,getString(R.string.string_positive_photo_tips2));
                    return;
                }
                if (TextUtils.isEmpty(photoUrl2)){
                    ToastUtils.showLong(this,getString(faceCompare?R.string.string_negative_photo_tips2:R.string.string_positive_signature_photo_tips3));
                    return;
                }

                KycApi.RequestKycPhotoVerify(photoUrl,faceCompare?photoUrl2:"",faceCompare?"":photoUrl2,new SimpleResponseListener<LvTwoSubmitResponse>(){
                    @Override
                    public void onBefore() {
                        super.onBefore();
                        getUI().showProgressDialog("","");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        getUI().dismissProgressDialog();
                    }

                    @Override
                    public void onSuccess(LvTwoSubmitResponse response) {
                        super.onSuccess(response);
                        if (CodeUtils.isSuccess(response,true)) {
                            if (faceCompare) {
                                SdkPrepareInfoBean sdkPrepareInfo = response.getSdkPrepareInfo();
                                if (sdkPrepareInfo != null) {
                                    goDetectFace(sdkPrepareInfo);
                                }else{
                                    ToastUtils.showLong(AuthenticateSubmitActivity.this,getString(R.string.string_no_face_info));
                                }
                            }else{
                                ToastUtils.showLong(AuthenticateSubmitActivity.this,getString(R.string.string_submit_success));
                                setResult(RESULT_OK);
                                finish();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable error) {
                        super.onError(error);
                    }
                });


                break;
        }
    }

    //活体检测
    private void goDetectFace(SdkPrepareInfoBean sdkPrepareInfo) {
        //TODO
        openCloudFaceService(sdkPrepareInfo);
    }

    @Override
    public void requestUserInfoSuccess(UserInfoBean userInfo) {
        if (userInfo != null) {
            bindGA = userInfo.isBindGA();
            mobile = userInfo.getMobile();
            email = userInfo.getEmail();
            final boolean isBindMobile = !TextUtils.isEmpty(mobile) && userInfo.getRegisterType() != 1;
            final boolean isBindEmail = !TextUtils.isEmpty(email) && userInfo.getRegisterType() != 2;

            VerifyUtil.is2FA(this, userInfo, new VerifyUtil.VerifyListener() {
                @Override
                public void on2FAVerify(boolean isVerify2FA) {
                    if (!isVerify2FA) {
                        //没有二次绑定认证
                        return;
                    }else{
                        //去二次验证
                        IntentUtils.goTwoVerify(AuthenticateSubmitActivity.this, REQUEST_CODE_TWO_VERIFY, "from_kyc", "", "10", bindGA, isBindMobile, isBindEmail, isVerifyEmail);
                    }
                }
            });

        }
    }

    @Override
    public void updateKycConfig(KycInfoConfigResponse response) {
        if (response != null) {
            if (!faceCompare) {
                KycInfoConfigResponse.KycSettingsBean custKycSettings = response.getKycSettings();
                if (custKycSettings != null) {
                    KycInfoConfigResponse.KycSettingsBean.Level2Bean kycConfigInfo = custKycSettings.getLevel2();
                    if (kycConfigInfo != null) {
                        authImg1Title.setText(kycConfigInfo.getFrontTitle());
                        authImg2Title.setText(kycConfigInfo.getHoldTitle());
                        authImg1Tips.setText(kycConfigInfo.getFrontDescription());
                        authImg2Tips.setText(kycConfigInfo.getHoldDescription());
                        totalTips.setText(kycConfigInfo.getExtDescription());
                        loadImg(authImg1Example,kycConfigInfo.getFrontBackground());
                        loadImg(authImg2Example,kycConfigInfo.getHoldBackground());
                    }
                }
            }
        }

    }

    private void loadImg(ImageView imageView, String url) {
        if (!TextUtils.isEmpty(url)) {
            CImageLoader.getInstance().load(imageView,url);
        }
    }

    /**
     * 选择图片
     */
    private void showSelectPhoto(final boolean firstPhoto) {
        if(selectPhotoAlert != null && selectPhotoAlert.isShowing())
            return;
        selectPhotoAlert = new AlertView(null, null, getString(R.string.string_cancel), null, selectPhotoWayArray, this, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == -1) {
                    return;
                }
                if (position==0){
                    //拍照
                    startSelectImage(true, firstPhoto);
                }else{
                    //从相册选择
                    startSelectImage(false, firstPhoto);
                }
            }
        });
        selectPhotoAlert.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
            }
        });
        selectPhotoAlert.show();
    }

    private void startSelectImage(boolean bCamera, final boolean bFirstPhoto){
//        ImgPickHelper.getInstance().clearCachedCropFile(AuthenticateSubmitActivity.this);
        ImgPickHelper.getInstance().registeHandler(new ImgPickHandler() {

            @Override
            public void onSuccess(Uri uri) {
                uploadImage(uri, bFirstPhoto);
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onFailed(String message) {


            }
        });
        ImgPickHelper.getInstance().needCrop(false);
        if (bCamera) {
            String[] perms = {Manifest.permission.CAMERA};
            if (!EasyPermissions.hasPermissions(this, perms)) {
                EasyPermissions.requestPermissions(this, getString(R.string.file_permission_hint), CAMERA_PERMISSION_REQUEST_CODE, perms);
            }else{
                ImgPickHelper.getInstance().goCamera(this);
            }

            /*if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
                    Toast.makeText(getContext(), "please give me the permission", Toast.LENGTH_SHORT).show();
                } else {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
                }
            } else {
                ImgPickHelper.getInstance().goCamera(getActivity());
            }*/

        } else {
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (!EasyPermissions.hasPermissions(this, perms)) {
                EasyPermissions.requestPermissions(this, getString(R.string.file_permission_hint), WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE, perms);
            }else{
                ImgPickHelper.getInstance().goGallery(this);
            }
            /*if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    Toast.makeText(getContext(), "please give me the permission", Toast.LENGTH_SHORT).show();
                } else {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
                }
            } else {
                ImgPickHelper.getInstance().goGallery(getActivity());
            }*/
        }

    }

    //public String IMAGE_TEMP_PATH =  "/image_temp.jpg";//
    //public String IMAGE_TEMP_PATH2 =  "/image_temp1.jpg";//

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ImgPickHelper.getInstance().handleResult(this, requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_TWO_VERIFY && resultCode == RESULT_OK) {
            //二次验证成功，下一步，发起请求提币
            if (data != null) {
                if (TextUtils.isEmpty(photoUrl)){
                    ToastUtils.showLong(this,getString(R.string.string_positive_photo_tips2));
                    return;
                }
                if (TextUtils.isEmpty(photoUrl2)){
                    ToastUtils.showLong(this,getString(R.string.string_positive_signature_photo_tips3));
                    return;
                }
                TwoVerifyBean twoVerify = (TwoVerifyBean) data.getSerializableExtra("twoVerify");

//                SecurityApi.authKYC(country,firstName,lastName,idType,id,gender,photoUrl,photoUrl2,twoVerify.getAuth_type(),twoVerify.getOrder_id(),twoVerify.getVerify_code(),new SimpleResponseListener<ResultResponse>(){
//                    @Override
//                    public void onSuccess(ResultResponse response) {
//                        super.onSuccess(response);
//                        if (CodeUtils.isSuccess(response,true)) {
//                            ToastUtils.showLong(AuthenticateSubmitActivity.this,getString(R.string.string_submit_success));
//                            setResult(RESULT_OK);
//                            finish();
//                        }
//                    }
//                });
            }
        }
    }

    private void uploadImage(final Uri fromUri, final boolean bFirstPhoto) {
        if(fromUri == null)
            return;
        if (FileTools.fileIsExists(fromUri.getPath())) {
            //if(mJSImageCallback != null){
            UtilsApi.UploadVerifyImg(fromUri.getPath(), new SimpleResponseListener<UploadImgResponse>() {

                @Override
                public void onBefore() {
                    super.onBefore();
                    getUI().showProgressDialog("", getString(R.string.string_uploading));
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    getUI().dismissProgressDialog();
                }

                @Override
                public void onSuccess(UploadImgResponse response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response, true)) {
                        if (bFirstPhoto) {
                            photoUrl = response.getUrl();
                            Glide.with(AuthenticateSubmitActivity.this)
                                    .load(fromUri.getPath())
                                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                                    .skipMemoryCache(true)
                                    .into(photoImg1);
                        } else {
                            Glide.with(AuthenticateSubmitActivity.this)
                                    .load(fromUri.getPath())
                                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                                    .skipMemoryCache(true)
                                    .into(photoImg2);
                            photoUrl2 = response.getUrl();
                        }

                        ToastUtils.showLong(AuthenticateSubmitActivity.this, getString(R.string.string_upload_success));

                    }
                }

                @Override
                public void onError(Throwable error) {
                    ToastUtils.showLong(AuthenticateSubmitActivity.this,getString(R.string.string_upload_failed));
                }

            });
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
//        requestCodeQRCodePermissions();
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE){
            //takingPicture();
            ImgPickHelper.getInstance().goCamera(this);
        } else if (requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
            //mSourceIntent = ImageUtils.choosePicture();
            //startActivityForResult(mSourceIntent, FILECHOOSER_RESULTCODE);
            ImgPickHelper.getInstance().goGallery(this);
        } else {
            Toast.makeText(this, "request permission fail!", Toast.LENGTH_SHORT).show();
        }
    }

/*    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            ImgPickHelper.getInstance().goCamera(this);
        } else if (requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            ImgPickHelper.getInstance().goGallery(this);
        } else {
            Toast.makeText(this, "request camara permission fail!", Toast.LENGTH_SHORT).show();
        }
    }*/

    @Override
    public void onDestroy() {
        super.onDestroy();
        ImgPickHelper.getInstance().unregistHandler();
    }

    //有faceId和sign 拉起sdk
    public void openCloudFaceService(SdkPrepareInfoBean sdkPrepareInfo) {
        getUI().showProgressDialog("","");
        Bundle data = new Bundle();
        WbCloudFaceVerifySdk.InputData inputData = new WbCloudFaceVerifySdk.InputData(
                sdkPrepareInfo.getFaceId(),
                sdkPrepareInfo.getOrderNo(),
                sdkPrepareInfo.getAppId(),
                sdkPrepareInfo.getVersion(),
                sdkPrepareInfo.getNonce(),
                sdkPrepareInfo.getUserId(),
                sdkPrepareInfo.getSign(),
                FaceVerifyStatus.Mode.REFLECTION,
                sdkPrepareInfo.getLicense());

        data.putSerializable(WbCloudFaceContant.INPUT_DATA, inputData);
        //是否展示刷脸成功页面，默认展示
        data.putBoolean(WbCloudFaceContant.SHOW_SUCCESS_PAGE, true);
        //是否展示刷脸失败页面，默认展示
        data.putBoolean(WbCloudFaceContant.SHOW_FAIL_PAGE, true);
        //颜色设置
        data.putString(WbCloudFaceContant.COLOR_MODE, WbCloudFaceContant.BLACK);
        //是否录制视频存证
        //默认录制
        data.putBoolean(WbCloudFaceContant.VIDEO_UPLOAD, false);
        //是否对录制视频进行检查,默认不检查
        data.putBoolean(WbCloudFaceContant.VIDEO_CHECK, false);
        //是否开启闭眼检测，默认不开启
        data.putBoolean(WbCloudFaceContant.ENABLE_CLOSE_EYES,true);
        //设置选择的比对类型  默认为公安网纹图片对比
        //公安网纹图片比对 WbCloudFaceVerifySdk.ID_CRAD
        //自带比对源比对  WbCloudFaceVerifySdk.SRC_IMG
        //仅活体检测  WbCloudFaceVerifySdk.NONE
        //默认公安网纹图片比对
        data.putString(WbCloudFaceContant.COMPARE_TYPE, WbCloudFaceContant.SRC_IMG);
//        data.putString(WbCloudFaceContant.COMPARE_TYPE, WbCloudFaceContant.ID_CARD);
        //动态下载model
//        data.putString(WbCloudFaceContant.YT_MODEL_LOC, "/storage/emulated/0/srcPhoto");


        WbCloudFaceVerifySdk.getInstance().initSdk(this, data, new WbCloudFaceVeirfyLoginListner() {
            @Override
            public void onLoginSuccess() {
                DebugLog.i(TAG, "onLoginSuccess");
                getUI().dismissProgressDialog();

                WbCloudFaceVerifySdk.getInstance().startWbFaceVeirifySdk(AuthenticateSubmitActivity.this, new WbCloudFaceVeirfyResultListener() {
                    @Override
                    public void onFinish(WbFaceVerifyResult result) {
                        if (result != null) {
                            if (result.isSuccess()) {
                                submitFaceVerifyResult(true,result.getOrderNo());
                                DebugLog.d(TAG, "刷脸成功! Sign=" + result.getSign() + "; liveRate=" + result.getLiveRate() +
                                        "; similarity=" + result.getSimilarity() + "userImageString=" + result.getUserImageString());
//                                 ToastUtils.showLong(AuthenticateSubmitActivity.this.getResources().getString(R.string.string_face_success));
                            } else {
//                                submitFaceVerifyResult(false,result.getOrderNo());
                                WbFaceError error = result.getError();
                                if (error != null) {
                                    DebugLog.d(TAG, "刷脸失败！domain=" + error.getDomain() + " ;code= " + error.getCode()
                                            + " ;desc=" + error.getDesc() + ";reason=" + error.getReason());
                                    if (error.getDomain().equals(WbFaceError.WBFaceErrorDomainCompareServer)) {
                                        DebugLog.d(TAG, "对比失败，liveRate=" + result.getLiveRate() +
                                                "; similarity=" + result.getSimilarity());
                                    }
//                                    ToastUtils.showLong( "face verify failed : " + error.getDesc());
                                } else {
                                    DebugLog.e(TAG, "sdk返回error为空！");
                                    ToastUtils.showLong(AuthenticateSubmitActivity.this.getResources().getString(R.string.string_face_failed));
                                }
                            }
                        } else {
                            DebugLog.e(TAG, "sdk返回结果为空！");
                            ToastUtils.showLong(AuthenticateSubmitActivity.this.getResources().getString(R.string.string_face_failed));
                        }
                        //测试用代码
                        //不管刷脸成功失败，只要结束了，自带对比和活体检测都更新userId
//                        if (!compareType.equals(WbCloudFaceContant.ID_CARD)) {
//                            DebugLog.d(TAG, "更新userId");
//                            userId = "WbFaceVerifyREF" + System.currentTimeMillis();
//                        }
                    }
                });
            }

            @Override
            public void onLoginFailed(WbFaceError error) {
                DebugLog.i(TAG, "onLoginFailed!");
                getUI().dismissProgressDialog();
                if (error != null) {
                    DebugLog.d(TAG, "登录失败！domain=" + error.getDomain() + " ;code= " + error.getCode()
                            + " ;desc=" + error.getDesc() + ";reason=" + error.getReason());
                    if (error.getDomain().equals(WbFaceError.WBFaceErrorDomainParams)) {
                        ToastUtils.showLong("传入参数有误！" + error.getReason());
                    } else {
                        ToastUtils.showLong("登录刷脸sdk失败！" + error.getDesc());
                    }
                } else {
                    DebugLog.e(TAG, "sdk返回error为空！");
                }
            }
        });
    }

    private void submitFaceVerifyResult(final boolean isFaceSuccess, String orderNo) {
        KycApi.RequestKycFaceVerify(orderNo,new SimpleResponseListener<ResultResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    if (isFaceSuccess) {
                        ToastUtils.showLong(getString(R.string.string_submit_success));
                        setResult(RESULT_OK);
                        finish();
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }
}
